# coding=utf-8
import time
import requests
import json
import random
from setting import SetTing
#import xlwings as xw
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select, WebDriverWait
# 谷歌浏览器无头浏览字段
chrome_op = webdriver.ChromeOptions()  
chrome_op.add_argument('--headless')
chrome_op.add_argument('--disable-gpu')
#火狐浏览器无头浏览字段
firefox_op =webdriver.FirefoxOptions()
firefox_op.add_argument('--headless')
firefox_op.add_argument('--disable-gpu')


class gl_getFQ:
    def __init__(self):
        st = SetTing()
        self.gv_name = st.name()  # 引入四项配置
        self.gv_password = st.password()
        self.gv_FQ_setting = st.FQ_setting()
        self.gv_FQ_forbid = st.FQ_forbid()
        self.gv_words_setting = st.words_setting()
        self.gv_post = st.post_setting() #是否多岗位设置
        self.gv_mobiles=st.mobiles()#@多手机号设置

        self.gv_jf = 1  # 核算岗待办页码指向
        self.gv_i = 1  # 单据指向
        self.gv_choose_page = ''
        self.gv_choose = ''  # 核算岗目录表格中的选择项
        self.gv_FQ_send = ''  # 是否抢单标记
        self.gv_FQ = ''  # FQ号
        self.gv_FQ_headertxt = ''  # FQ的服务请求描述
        self.gv_FQ_row = 1  # 导出excel文件行数
        self.gv_FQ_list = []  # 本次运行抢单FQ列表,用于避免重复
        self.gv_excel_path = ''  # 当日导出excel路劲
        self.gv_refresh_num = 1  # 刷新次数
        self.gv_FQ_time = ''  # 抢单时间

    def sendmsg(self, msg='', at_mobiles=[], atall=False):
        '''测试机器人发送消息,第一个参数是推送消息内容,第二个参数为at手机号,第三个参数是否at全员'''
        url = 'https://oapi.dingtalk.com/robot/send?access_token=fc1f13b5250a7f1aff95185fa364c652a1350cec827fce7e9a493298ed63c9c9'
        header1 = {"Content-Type": "application/json;charset-utf-8"}
        string_textmsg = {
            "msgtype": "text",
            "text": {"content": msg},
            "at": {"isAtAll": atall}
        }
        if at_mobiles:
            at_mobiles = list(map(str, at_mobiles))
            string_textmsg["at"]["atMobiles"] = at_mobiles

        string_textmsg = json.dumps(string_textmsg)
        requests.post(url, data=string_textmsg, headers=header1)

    def creat_excel(self):  # 打开当天excel,否则创建,写入首行,测量行数,末行写入
        self.gv_excel_path = 'export/' + \
            time.strftime('%Y-%m-%d', time.localtime(time.time())
                          ) + '抢单清单.xlsx'
        try:
            xw.Book(self.gv_excel_path)
        except:
            xw.Book().save(self.gv_excel_path)
        xw.Book(self.gv_excel_path).sheets(1).range(
            'A1').value = ['是否抢单', 'FQ', '抬头文本', '抢单时间']
        row = xw.Book(self.gv_excel_path).sheets(1).range('A1', 'A2000').value
        for item in row:
            if item == None:
                break
            self.gv_FQ_row += 1
        xw.Book(self.gv_excel_path).save()

    def login(self):  # 登录函数,用于登录流程处理
        global gl_driver
        # gl_driver = webdriver.Chrome(chrome_options=chrome_op)  # 谷歌无头浏览
        # gl_driver = webdriver.Chrome()

        gl_driver = webdriver.Firefox(firefox_options=firefox_op) #火狐无头浏览
        #gl_driver = webdriver.Firefox()

        gl_driver.maximize_window()
        gl_driver.get("http://fso.sinopec.com")
        if "FSO" in gl_driver.title:
            user = gl_driver.find_element_by_name("j_username")
            user.clear()
            user.send_keys(self.gv_name)
            password = gl_driver.find_element_by_name("j_password")
            password.clear()
            password.send_keys(self.gv_password, Keys.ENTER)

        if self.gv_post:  # 多重岗位判定
            try:
                WebDriverWait(gl_driver, 10).until(
                    EC.presence_of_element_located((By.ID, "ZAIC_AG_NJ_4")))
            finally:
                pass
            time.sleep(1)
            gl_driver.find_element_by_id("ZAIC_AG_NJ_1").click()  # 点击审核岗

        try:
            WebDriverWait(gl_driver, 10).until(EC.presence_of_element_located(
                (By.ID, "CRMApplicationFrame")))  # 判定至目标页面
        finally:
            pass

    def refresh(self):  # 刷新函数,用于单个流程派工完后的界面刷新
        gl_driver.switch_to.default_content()  # 切换到顶层框架
        gl_driver.switch_to.frame('CRMApplicationFrame')
        try:
            WebDriverWait(gl_driver, 10).until(
                EC.presence_of_element_located((By.ID, "WorkAreaFrame1")))  # 判定至目标页面
        finally:
            pass
        gl_driver.switch_to.frame('WorkAreaFrame1')
        try:
            WebDriverWait(gl_driver, 10).until(EC.presence_of_element_located(
                (By.ID, "C4_W17_V18_IC-MGRHOME")))  # 判定至目标页面
        finally:
            pass
        time.sleep(3)
        gl_driver.find_element_by_id(
            "C4_W17_V18_IC-MGRHOME").click()  # 点击待办事项刷新
        time.sleep(4)
        print('\r  ...第%d次刷新页面...' % self.gv_refresh_num, end='')
        self.gv_refresh_num += 1

    def write_excel(self):  # 写入excel函数,一次写入一行
        if self.gv_FQ != '':
            self.gv_FQ_time = time.strftime('%Y-%m-%d %H:%M:%S')
            list1 = [self.gv_FQ_send, self.gv_FQ,
                     self.gv_FQ_headertxt, self.gv_FQ_time]
            xw.Book(self.gv_excel_path).sheets(1).range(
                'A'+str(self.gv_FQ_row)).value = list1
            xw.Book(self.gv_excel_path).save()
            self.gv_FQ_row += 1

    def dict1(self):  # 判定公司代码或者关键词是否存在
        for fq in self.gv_FQ_setting:
            if fq in self.gv_FQ:
                return True  # 函数执行return后会立刻返回,结束调用

        for fq in self.gv_FQ_forbid:
            if fq in self.gv_FQ:
                return False

        for word in self.gv_words_setting:
            if word in self.gv_FQ_headertxt:
                return True

    def dispatch_first(self):  # 核算岗待办清单
        self.gv_i = 1  # FQ条目数
        gl_driver.switch_to.default_content()  # 切换到顶层框架
        gl_driver.switch_to.frame('CRMApplicationFrame')
        try:
            WebDriverWait(gl_driver, 10).until(
                EC.presence_of_element_located((By.ID, "WorkAreaFrame1")))  # 判定至目标页面
        finally:
            pass

        gl_driver.switch_to.frame('WorkAreaFrame1')
        while True:
            try:
                WebDriverWait(gl_driver, 10).until(EC.presence_of_element_located(
                    (By.ID, "C17_W42_V43_ZSSFList__header_bee__1")))  # 判定至目标页面
            finally:
                pass

            if self.gv_jf != (self.gv_i-1)//10+1:  # 判断当前页码与FQ编号吻合
                self.gv_jf = (self.gv_i-1)//10+1  # 用于取得页数
                self.gv_choose_page = 'C17_W42_V43_ZSSFList_pag_pg-%d' % (
                    self.gv_jf)
                gl_driver.find_element_by_id(
                    self.gv_choose_page).click()  # 点击页码
                time.sleep(2)  # 翻页后调整

            self.gv_choose = 'C17_W42_V43_list_table[%d].' % (
                self.gv_i)  # FQ路径
            # time.sleep(2)

            try:  # 遍历完当前单据,主动报错,跳出流程循环.
                self.gv_FQ = gl_driver.find_element_by_id(
                    self.gv_choose+'fq_id').get_attribute('title')
            except:
                raise ValueError
            else:
                self.gv_FQ_headertxt = gl_driver.find_element_by_id(
                    self.gv_choose+'description').get_attribute('title')
            self.dispatch()

    def dispatch(self):
        if self.gv_FQ not in self.gv_FQ_list:  # 先判断是否在FQ列表里,用于避免重复操作同一笔FQ
            self.gv_FQ_list.append(self.gv_FQ)
            # print(self.gv_FQ)

            if self.dict1():
                time.sleep(1)
                gl_driver.find_element_by_id(
                    self.gv_choose+'object_id').click()  # 点击派工岗FQ

                try:
                    WebDriverWait(gl_driver, 10).until(EC.presence_of_element_located(
                        (By.ID, 'C25_W69_V71_V76_btadminh_struct.description')))  # 判定至目标页面
                except:
                    raise ValueError
                gl_driver.find_element_by_id('BackButton').click()
                self.gv_FQ_send = '已抢'
                #self.write_excel()
                print('\n' + self.gv_FQ + ' ' + self.gv_FQ_headertxt)
                print('  ' + self.gv_FQ_send)
                joke = {
                    1: '你的砖来了!',
                    2: '你的砖沙子来了!',
                    3: '你的墙要砌了!',
                    4: '你的钢筋要拧了!',
                    5: '你的水泥要搅拌了!',
                    6: '你的地基该挖了!',
                    7: '你的钱掉了!'
                }
                msg = joke.get(random.randint(1, 7)) + '\n'.join([self.gv_name ,self.gv_FQ , self.gv_FQ_headertxt])
                self.sendmsg(msg= msg ,at_mobiles = self.gv_mobiles)

                self.gv_FQ = ''
                self.gv_FQ_headertxt = ''
                self.gv_i = 1
            else:
                self.gv_FQ_send = '未抢'
                #self.write_excel()
                print('\n' + self.gv_FQ + ' ' + self.gv_FQ_headertxt)
                print('  ' + self.gv_FQ_send)
                self.gv_FQ = ''
                self.gv_FQ_headertxt = ''
                self.gv_i += 1

        else:  # 对于已在FQ列表中的FQ,跳过操作,进入下一轮循环
            self.gv_i += 1
            self.gv_FQ = ''

    def Main(self):
        #self.creat_excel()
        self.login()
        while True:  # 核算岗待办清单

            try:
                self.dispatch_first()
            except:
                pass

            try:
                self.refresh()
            except:
                gl_driver.quit()
                self.gv_refresh_num = 1
                print('\n  **********重 启 浏 览 器**********')
                self.login()
            finally:
                if self.gv_refresh_num > 400:
                    gl_driver.quit()
                    self.gv_refresh_num = 1
                    print('\n  **********重 启 浏 览 器**********')
                    self.login()


if __name__ == "__main__":
    gl = gl_getFQ()
    gl.Main()
